import { LoadingOutlined, PlusOutlined } from "@ant-design/icons";
import { message, Upload } from "antd";
import React, { useState } from "react";
import Cloud from 'leancloud-storage'

const getBase64 = (img, callback) => {
  //将本地文件资源对象、转换为base64编码
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result));
  reader.readAsDataURL(img);
};

const beforeUpload = (file) => {
  //上传文件类型、大小控制
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";

  if (!isJpgOrPng) {
    message.error("You can only upload JPG/PNG file!");
  }

  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isLt2M) {
    message.error("Image must smaller than 2MB!");
  }

  return isJpgOrPng && isLt2M;
};

const ImgUpload = (props) => {
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState();
  console.log('ImgUpload组件的props',props);
  let {value,onChange} = props
  const handleChange = (info) => {
    //监听action接口上传图片进度
    if (info.file.status === "uploading") {
      setLoading(true);
      return;
    }

    if (info.file.status === "done") {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, (url) => {
        setLoading(false);
        setImageUrl(url);
      });
    }
  };

  const handleUpload = (info) => {
    //自定义上传函数
    // console.log(info);
    getBase64(info.file, (base64) => {
      // console.log(base64);
      const file = new Cloud.File("img.png", {base64}); //将本地资源，转换为leanCloud资源对象
      file.save().then(res=>{ //上传图片资源
        // console.log(res);
        let {url} = res.attributes
        onChange(url)  //为表单内的这个自定义组件，设置value
        setImageUrl(url);
      })
    });
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div
        style={{
          marginTop: 8,
        }}
      >
        Upload
      </div>
    </div>
  );
  return (
    <Upload
      name="avatar"
      listType="picture-card"
      className="avatar-uploader"
      showUploadList={false}
      beforeUpload={beforeUpload}
      customRequest={handleUpload}
    >
      {imageUrl||value ? (
        <img
          src={imageUrl||value}
          alt="avatar"
          style={{
            width: "100%",
          }}
        />
      ) : (
        uploadButton
      )}
    </Upload>
  );
};

export default ImgUpload;
